import java.awt.Point;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.awt.image.SampleModel;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ImageReader {
	SampleModel sampleModel;
	File file;

	public ImageReader(File file) {
		this.file = file;
	}

	/** function which load image into array of integers  **/
	public int[][] getImageToArray()  {
		BufferedImage img=null;
		try {
			img = ImageIO.read(file);
		} catch (IOException e) {
			e.printStackTrace();
		}
	
		// if not RGB then transform into it
		if (img.getType() != BufferedImage.TYPE_INT_RGB) { 
		    BufferedImage tmp = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);
		    tmp.getGraphics().drawImage(img, 0, 0, null);
		    img = tmp;
		}
		
		Raster raster = img.getData();
		sampleModel = raster.getSampleModel();
		int w = raster.getWidth();
		int h = raster.getHeight();
		int pixels[][] = new int[w][h];
		
		//put data into array
		// NO SEPARATE COLUMNS FOR EACH COLOR => MAKES IT SIMPLER
		for (int col = 0; col < w; col++) {
			for (int row = 0; row < h; row++) {
				pixels[col][row] = raster.getSample(col, row, 0);
			}
		}

		return pixels;
	}

	
	/** Function which creates RGB image of name "processed" from array of integers
	 * @param grayscaleValues **/
	
	
	public WritableRaster createColoredRaster( int pixels[][], int[][] grayscaleValues )
	{
		int w=pixels.length;
	    int h=pixels[0].length;
		WritableRaster raster = Raster.createWritableRaster(sampleModel,new Point(0, 0));
		
		for (int i = 0; i < w; i++) {
			for (int j = 0; j < h; j++) {
				if (pixels[i][j] == Assignment4.DISTINGUISH_MAP_VALUE)
				{
					raster.setSample(i, j, 0, 255); //mark the points as red
				}
				else if (pixels[i][j]==Assignment4.ROBOT_COLOR){
					raster.setSample(i, j, 1, 255); //mark the point as green
				}
				else if ( grayscaleValues != null ){
					raster.setSample(i, j, 2, grayscaleValues[i][j]); 
					raster.setSample(i, j, 1, grayscaleValues[i][j]);
					raster.setSample(i, j, 0, grayscaleValues[i][j]);
				}
				else {//mark the points as black and white
					raster.setSample(i, j, 2, pixels[i][j]); 
					raster.setSample(i, j, 1, pixels[i][j]);
					raster.setSample(i, j, 0, pixels[i][j]);
				}
			}
		}
		return raster;
	}
	
	
	public void saveImage(int pixels[][], String name ) {
		saveImage( pixels, name, null );
	}
	public void saveImage(int pixels[][], String name, int grayscaleValues[][]) {
		int w=pixels.length;
	    int h=pixels[0].length;
		BufferedImage image = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB);
		image.setData(createColoredRaster(pixels, grayscaleValues));
		File output = new File(name);
		try {
			ImageIO.write(image, "png", output);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
